using Avalonia;
using Avalonia.Controls;
using Avalonia.Styling;
using DesktopApp.ViewModels; // For RuleItemViewModel, RuleEditorViewModel
using DesktopApp.Views; // For AboutWindow, RuleEditorWindow, ConfirmationDialog, InputDialog
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Avalonia.Platform.Storage; // Add this for file dialogs
using System.Collections.Generic; // Add this for List
using Avalonia.Controls.ApplicationLifetimes; // Add this

namespace DesktopApp.ViewModels.Services
{
    public class UIService : IUIService
    {
        private readonly IServiceProvider _serviceProvider;

        public UIService(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
        }

        private Window? GetOwner()
        {
            try
            {
                return _serviceProvider.GetService<MainWindow>();
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"UIService Error: Failed to resolve MainWindow: {ex.Message}");
                return null;
            }
        }

        public async Task ShowAboutDialogAsync()
        {
            var owner = GetOwner();
            var aboutWindow = new AboutWindow();
            if (owner != null)
            {
                await aboutWindow.ShowDialog(owner);
            }
            else
            {
                aboutWindow.Show(); // Show non-modally if owner not found
            }
        }

        public async Task<RuleItemViewModel?> ShowRuleEditorDialogAsync(RuleEditorViewModel editorViewModel)
        {
            var owner = GetOwner();
            if (owner == null)
            {
                Debug.WriteLine("UIService Error: Cannot show Rule Editor dialog without an owner window.");
                return null;
            }

            var editorWindow = new RuleEditorWindow
            {
                DataContext = editorViewModel
            };
            
            return await editorWindow.ShowDialog<RuleItemViewModel?>(owner);
        }

        public async Task<bool> ShowConfirmationDialogAsync(string title, string message)
        {
             var owner = GetOwner();
             if (owner == null)
             {
                 Debug.WriteLine("UIService Error: Cannot show Confirmation dialog without an owner window.");
                 return false; // Assume cancellation if owner not found
             }
             return await ConfirmationDialog.ShowAsync(owner, title, message);
        }

        public async Task<string?> ShowInputDialogAsync(string title, string label, string defaultValue = "")
        {
             var owner = GetOwner();
             if (owner == null)
             {
                 Debug.WriteLine("UIService Error: Cannot show Input dialog without an owner window.");
                 return null; // Assume cancellation if owner not found
             }
             return await InputDialog.ShowAsync(owner, title, label, defaultValue);
        }

        public void ApplyTheme(ThemeVariant themeVariant)
        {
            if (Application.Current is null) return;
            
            if (Application.Current.RequestedThemeVariant != themeVariant)
            {
                Application.Current.RequestedThemeVariant = themeVariant;
                Debug.WriteLine($"UIService: Theme applied: {themeVariant}");
            }
        }

        public Task<bool> OpenUrlAsync(string url)
        {
            try
            {
                // Use ShellExecute to open the URL in the default browser, works cross-platform
                Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
                Debug.WriteLine($"UIService: Opening URL: {url}");
                return Task.FromResult(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"UIService: Error opening URL '{url}': {ex.Message}");
                // TODO: Optionally show an error message to the user via a dialog?
                return Task.FromResult(false);
            }
        }

        // Helper to get TopLevel for storage provider
        private TopLevel? GetTopLevel()
        {
            // Try to get the owner window first
            var owner = GetOwner();
            if (owner != null) return owner;

            // Fallback if owner not found (e.g., during startup or if DI setup changes)
            if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
            {
                return desktop.MainWindow;
            }
            // If running in a single view app lifetime
            if (Application.Current?.ApplicationLifetime is ISingleViewApplicationLifetime singleView)
            {
                 return TopLevel.GetTopLevel(singleView.MainView);
            }
            // Add other lifetime checks if necessary
            return null;
        }

        public async Task<IStorageFile?> ShowOpenFileDialogAsync(string title, List<FilePickerFileType>? filters = null)
        {
            var topLevel = GetTopLevel();
            if (topLevel == null)
            {
                 Debug.WriteLine("UIService Error: Could not find TopLevel for ShowOpenFileDialogAsync.");
                 return null;
            }

            var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
            {
                Title = title,
                AllowMultiple = false,
                FileTypeFilter = filters // Pass filters if provided
            });

            return files?.Count >= 1 ? files[0] : null;
        }

        public async Task<IStorageFile?> ShowSaveFileDialogAsync(string title, string? defaultExtension = null, string? suggestedFileName = null, List<FilePickerFileType>? filters = null)
        {
            var topLevel = GetTopLevel();
            if (topLevel == null)
            {
                Debug.WriteLine("UIService Error: Could not find TopLevel for ShowSaveFileDialogAsync.");
                return null;
            }

            return await topLevel.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
            {
                Title = title,
                DefaultExtension = defaultExtension,
                SuggestedFileName = suggestedFileName,
                FileTypeChoices = filters // Pass filters if provided
            });
        }
    }
} 